package Javafoundation;

public class Node {
    private int data;
    Node left;
    Node right;
    private Node root;

    public Node(int data) {
        this.data = data;
        left=null;
        right=null;
    }

    public void setData(int data) {
        this.data = data;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public int getData() {
        return data;
    }

    public Node getLeft() {
        return left;
    }

    public Node getRight() {
        return right;
    }
    public void print(){
        if(this.left!=null){
            this.left.print();
        }
        System.out.print(data+" ");
        if(this.right!=null){
            this.right.print();
        }
    }

    public Node remove(Node root,int target)
    {
        Node result = root;

        if (target==root.getData())
        {
            if (left == null && right == null)
                result = null;
            else if (left != null && right == null)
                result = (Node)left;
            else if (left == null && right != null)
                result = (Node)right;
            else
            {
                result = getSuccessor();
                result.left = left;
                result.right = right;
            }
        }
        else if (target<root.getData())
        {if (left != null)
            left = left.remove(left,target);
        else
        {if (right != null)
        {right = right.remove(right,target);} }}
        else if (target>root.getData())
            if (left != null)
                left = left.remove(left,target);
            else
            if (right != null)
                right = ((Node)right).remove(right,target);

        return result;
    }


    protected Node getSuccessor()
    {
        Node successor = (Node)right;

        while (successor.getLeft() != null)
            successor = (Node) successor.getLeft();

        ((Node)right).remove (right,successor.getData());

        return successor;
    }

}
